package com.hmdp.lock.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import com.hmdp.lock.ILock;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    // 业务名称，为了让锁有不同名称，不同业务有不同的锁
    private String name;
    // 锁统一前缀
    private static final String KEY_PREFIX = "lock:";
    // 线程ID前缀
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private StringRedisTemplate stringRedisTemplate;

    // 构造函数注入
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate){
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public boolean tryLock(long timeoutSec){
        // 获取线程标示
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁
        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success); // BooleanUtil.isTrue(success);底层就是这个
    }

    @Override
    public void unlock(){
        // 先获取线程标示
        String threadId = ID_PREFIX + Thread.currentThread().getId();
        // 获取锁中线程标示
        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        // 判断是否和当前线程一致
        if (threadId.equals(id)) {
            // 释放锁
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }
    }
}
